package utils;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpClinetUtils {
       //post get del put

    public static String doPost(String url, Map<String,String> params){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result="";
        CloseableHttpResponse httpResponse =null;
        try {

            HttpPost httpPost = new HttpPost(url);
            if(params!=null){
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for(Map.Entry<String,String> param : params.entrySet()){
                    paramList.add(new BasicNameValuePair(param.getKey(),param.getValue()));
                }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramList,Charset.defaultCharset());
                httpPost.setEntity(formEntity);
            }

            httpResponse = httpClient.execute(httpPost);
            result = EntityUtils.toString(httpResponse.getEntity(),Charset.defaultCharset());

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            close(httpClient,httpResponse);
        }

        return result;
    }

    private static void close(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse){
      if(null!=httpResponse){
           try {
               httpResponse.close();
           }catch (Exception e){
               e.printStackTrace();
           }
      }

        if(null!=httpClient){
            try {
                httpClient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        Map<String,String> params = new HashMap<String,String>();
        params.put("mobile","13218013652");
        params.put("tpl_id","");
        params.put("tpl_value","%23code%23%3d431515");
        params.put("key","");
        params.put("dtype","json");

        System.out.println(HttpClinetUtils.doPost("http://v.juhe.cn/sms/send",params));

    }

}
